package com.alter.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alter.auth.annotation.Authorization;
import com.alter.auth.annotation.CurrentUser;
import com.alter.auth.manager.TokenManager;
import com.alter.auth.model.TokenModel;
import com.alter.domain.UserInfo;
import com.alter.service.UserInfoService;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * @描述: 
 * @作者: alter
 * @时间：2017-8-22 下午9:10:48
 */

@RestController
@RequestMapping("/tokens")
public class TokenController {

	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
    private TokenManager tokenManager;
	
	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(value = "登录")
	public JSONObject login(@RequestParam("login_id") String loginId, @RequestParam String password){
		JSONObject data = new JSONObject();
		Assert.notNull(loginId, "username can not be empty");
        Assert.notNull(password, "password can not be empty");
		
        UserInfo userInfo = userInfoService.getUserInfo(loginId);
        if(userInfo == null || !userInfo.getPsw().equals(password)){
        	data.put("ret", -1001);
        	data.put("msg", "用户名或密码错误");
        	data.put("data", "");
        	return data;
        }
        //生成一个token，保存用户登录状态
        TokenModel model = tokenManager.createToken(userInfo.getLoginId());
        data.put("ret", 1);
    	data.put("msg", "success");
    	data.put("data", model);
		return data;
	}
	
	@RequestMapping(method = RequestMethod.DELETE)
	@Authorization
    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public JSONObject logout(@CurrentUser UserInfo userInfo) {
		JSONObject data = new JSONObject();
        tokenManager.deleteToken(userInfo.getId());
        data.put("ret", 1);
    	data.put("msg", "success");
    	data.put("data", "");
		return data;
    }
	
}
